package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pojo.Book;
import util.DBUtil;
import dao.BookDao;

public class BookDaoImpl implements BookDao {
	
	@Override
	public Book load(String id) {
		String sql = "select * from books where id=?";
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Book b = null;
		
		try {
			conn = DBUtil.createConnection();
			pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			
			rs = pst.executeQuery();
			if (rs.next()) {
				b = new Book(rs.getString("id"), rs.getString("bname"), rs.getString("img_path"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, pst, null);
		}
		return b;
	}

	@Override
	public List<Book> findAll() {
		String sql = "select * from books";
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Book> result = new ArrayList<>();
		
		try {
			conn = DBUtil.createConnection();
			pst = conn.prepareStatement(sql);
			
			rs = pst.executeQuery();
			while (rs.next()) {
				Book b = new Book(rs.getString("id"), rs.getString("bname"), rs.getString("img_path"));
				result.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, pst, null);
		}
		return result;
	}

}
